<template>
	<BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="50%" @ok="handleSubmit">
		<BasicForm @register="registerForm"> </BasicForm>
		<!-- <TreeSelect
			:tree-data="treeData"
			placeholder="Please select"
			:load-data="onLoadData"
			:fieldNames="{ value: 'menuId', label: 'title' }"
		/> -->
	</BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { TreeSelect } from 'ant-design-vue';
import { ApiTreeSelect, BasicDrawer, BasicForm } from '#/components';
import { formSchema } from './menu.data';
import { useDrawerInner, useForm } from '#/hooks';

import { getBackMenuLazyTree, saveBackMenu, updateBackMenu } from '@/api/sys/menu';
import { useMessage } from '@/hooks/web/useMessage';

export default defineComponent({
	name: 'MenuDrawer',
	components: { BasicDrawer, BasicForm, ApiTreeSelect, TreeSelect },
	emits: ['success', 'register'],
	setup(_, { emit }) {
		const isUpdate = ref(true);
		let treeData = ref<any>([]);
		const currentParentId = ref(0);
		const currentMenuId = ref(0);

		const { createMessage } = useMessage();

		const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
			labelWidth: 100,
			schemas: formSchema,
			showActionButtonGroup: false,
			baseColProps: { lg: 12, md: 24 },
		});

		const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
			resetFields();
			setDrawerProps({ confirmLoading: false });
			isUpdate.value = !!data?.isUpdate;

			console.log(data.record);
			if (unref(isUpdate)) {
				currentParentId.value = data.record?.parentId;
				currentMenuId.value = data.record.menuId;
			}

			if (unref(isUpdate)) {
				setFieldsValue({
					...data.record,
				});
			}
		});

		const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

		async function handleSubmit() {
			try {
				const values = await validate();

				values.parentId = Number(values.parentName) ? Number(values.parentName) : currentParentId.value;

				// 一级菜单没有以/开头 或者 非一级菜单以/开头
				if (
					(values.parentId && values.path.startsWith('/')) ||
					(!values.parentId && !values.path.startsWith('/'))
				) {
					createMessage.error('请输入正确的路由地址');
					return;
				}
				// 一级菜单但是组件不是layout
				if (!values.parentId && values.component.toUpperCase() !== 'LAYOUT') {
					createMessage.error('请输入正确的组件路径');
					return;
				}
				values.parentId ? (values.parentId = Number(values.parentId)) : (values.parentId = 0);
				delete values.parentName;

				setDrawerProps({ confirmLoading: true });

				if (unref(isUpdate)) {
					await updateBackMenu(currentMenuId.value, values);
				} else {
					await saveBackMenu(values);
				}
				closeDrawer();
				emit('success');
			} finally {
				setDrawerProps({ confirmLoading: false });
			}
		}

		// function onLoadData(treeNode) {
		// 	return new Promise<void>(resolve => {
		// 		if (treeNode.dataRef?.children) {
		// 			resolve();
		// 			return;
		// 		}

		// 		getBackMenuLazyTree<Recordable[]>(treeNode.dataRef.menuId).then(data => {
		// 			data.map(item => {
		// 				item.isLeaf = false;
		// 				item.value = item.menuId;
		// 			});
		// 			treeNode.dataRef.children = data;
		// 			treeData.value = [...treeData.value];
		// 			resolve();
		// 		});
		// 	});
		// }

		return { registerDrawer, registerForm, getTitle, handleSubmit, getBackMenuLazyTree, treeData };
	},
});
</script>
